import numpy as np
import pandas as pd
import os
import json
import time
pd_data = {}
pd_list = []


def fomat_files(file_path):
    global pd_data
    pd_data = pd.read_excel(file_path)
    # pd_data.head(10)
    pd_colm = pd_data.columns
    pd_colm = list(pd_colm)
    print(pd_colm)
    #  id	bond_code	quote_source	quote_side	quote_type	volume yield quote_status	 quote_time	leg_party	  	cb_valuation	 	is_cnex_trade_revoke	 	 	msg_id	is_deleted	add_date	create_time	 	creater_name
    # "id" in pd_colm & "bond_code" in pd_colm & "quote_source" in pd_colm & "quote_side" in pd_colm & "quote_type" in pd_colm & "volume" in pd_colm & "yield" in pd_colm & "quote_status" in pd_colm & "quote_time" in pd_colm & "leg_party" in pd_colm & "cb_valuation" in pd_colm & "is_cnex_trade_revoke" in pd_colm & "msg_id" in pd_colm & "is_deleted" in pd_colm & "add_date" in pd_colm & "create_time" in pd_colm & "creater_name" in pd_colm
    # quote_time create_time
    if ("id" in pd_colm) & ("bond_code" in pd_colm) & ("add_date" in pd_colm) & ("leg_party" in pd_colm) & ("quote_side" in pd_colm) & ("yield" in pd_colm) & ("quote_time" in pd_colm) & ("create_time" in pd_colm):
        return True
    else:
        return False


def get_all_data(key):
    global pd_data
    # pd_data = pd.read_excel(file_path)
    # "leg_party"
    pd_list = pd_data[key].unique()
    return pd_list


def get_select_date_list(val, key):
    global pd_data
    # pd_data = pd.read_excel(file_path)
    pd_list = pd_data["leg_party"].isin([val])
    # pd_list = pd_titles["add_date"].unique()
    # "leg_party"
    pd_list = pd_data[pd_list][key].unique()
    return pd_list


def get_select_double(object=[]):
    global pd_data
    global pd_list
    # key: "leg_party" value:
    # key: "add_date" value:
    pd_titles = pd_data[object[0]["keys"]].isin([object[0]["values"]])
    pd_index = pd_data[pd_titles]
    # pd_data = pd_index
    pd_idate = pd_index[object[1]["keys"]].isin([object[1]["values"]])
    pd_list = pd_index[pd_idate]
    return pd_list


def complie_bp():
    global pd_data
    global pd_list
    pd_list = pd_list["bond_code"].unique()
    # for val in :
    #     val


def complie_bp_toarr():
    global pd_data
    global pd_list
    object_list = []
    pd_bond_code_list = pd_list["bond_code"].unique()
    for val in pd_bond_code_list:
        pd_indx = pd_list["bond_code"].isin([val])
        print("获取遍历的内容1:", pd_indx,  val)
        # print("获取遍历的内容2:", pd_indx)
        pd_bonds = pd_list[pd_indx]
        side_lens = pd_bonds["quote_side"].nunique()
        print("遍历匹配到的内容:", pd_bonds, val, pd_bonds)
        #         quote_time
        # pd_bonds["quote_side"].nunique()
        if side_lens <= 1:
            # pass
            print("获取遍历的内容3:",   pd_bonds[:1]
                  ["quote_side"], pd_bonds[:-1]["quote_side"])
            # quote_side
            if str(pd_bonds[:-1]["quote_side"]) == 1:
                object = {
                    "type0_yield": 0, "type1_yield": pd_bonds[:-1]["yield"], "bond_code": pd_bonds[:-1]["bond_code"], "timestart": str(str(pd_bonds[:1]["quote_time"]).split(" ")[0]+" 08:00:00"), "timeend": str(pd_bonds[:-1]["quote_time"])
                }
                object_list.push(object)
            # if len(pd_bonds) > 2:
            if str(pd_bonds[:-1]["quote_side"]) == 0:
                pd_val = pd_bonds[:1]

                object = {
                    "type0_yield": pd_val["yield"], "type1_yield": 0, "bond_code": pd_val["bond_code"], "timestart": str(pd_bonds[:1]["quote_time"]), "timeend": str(str(pd_val["quote_time"]).split(" ")[0]+" 20:00:00")
                }
                object_list.push(object)
        else:
            # for val1 in pd_bonds.itertuples():
            objects = {"type0_yield": 0, "type1_yield": 0,
                       "bond_code": 0, "timestart": 0, "timeend": 0}
            for i in range(0, len(pd_bonds)):
                # pd_bonds.iloc[i]['c1'], pd_bonds.iloc[i]['c2']
                # print("获取每个bond_code里的内容: ", pd_bonds.iloc[i])
                # objects["bond_code"] = val
                valx = pd_bonds.iloc[i]
                if valx["quote_side"] == 0:
                    #                 yield
                    # if objects["type0_yield"] != 0:
                    objects["type0_yield"] = valx["yield"]
                    objects["bond_code"] = valx["bond_code"]
                    objects["timestart"] = str(valx["quote_time"])
                elif valx["quote_side"] == 1:
                    if objects["type1_yield"] == 0:
                        objects["type1_yield"] = valx["yield"]
                        objects["bond_code"] = valx["bond_code"]
                        objects["timeend"] = str(valx["quote_time"])
                        if objects["type0_yield"] != 0:
                            object_list.append(json.loads(json.dumps(objects)))
                            objects = {"type0_yield": objects['type0_yield'], "type1_yield": 0,
                                       "bond_code": objects['bond_code'], "timestart": objects['timestart'], "timeend": 0}
                            continue
                        else:
                            objects["type0_yield"] = 0
                            objects["type1_yield"] = valx["yield"]
                            objects["bond_code"] = valx["bond_code"]
                            objects["timestart"] = str(
                                str(str(valx["quote_time"]).split(" ")[0])+" 20:00:00")
                            objects["timeend"] = str(valx["quote_time"])
                            object_list.append(json.loads(json.dumps(objects)))
                            objects = {"type0_yield": 0, "type1_yield": 0,
                                       "bond_code": 0, "timestart": 0, "timeend": 0}
                            continue
            if (objects["type0_yield"] != 0) & (objects["type1_yield"] != 0):
                # object = {
                #     "type0_yield": pd_val["yield"], "type1_yield": 0, "bond_code": pd_val["bond_code"], "timestart": str(pd_bonds[:1]["quote_time"]), "timeend": str(str(pd_val["quote_time"]).split(" ")[0]+" 20:00:00")
                # }
                objects["timeend"] = str(
                    str(str(objects["timestart"]).split(" ")[0])+" 20:00:00")
                object_list.append(objects)
    arr_box = []
    for val in object_list:
        if val["bond_code"] not in arr_box:
            arr_box.append(val["bond_code"])
    arr_object_list = {}
    for val in arr_box:
        for val1 in object_list:
            if val1["bond_code"] == val:
                # tins = []
                # tins.append(val1)
                keys = """{0}""".format(val)
                print("我擦不科学:", keys)
                if keys not in arr_object_list:
                    arr_object_list[keys] = []
                arr_object_list[keys].append(val1)
                # .append(val1)
                # arr_object_list.append(options)
    print("获取arr_object_list的全部内容:", arr_object_list)
    print(len(arr_object_list))
    # for val in arr_object_list:
    #     val
    for val in arr_object_list:
        print("格式化后的数据:", val,)
        for val1 in arr_object_list[val]:
            # type0_yield 0状态下的 yield对应的值
            # type1_yield 1状态下的 yield对应的值
            # bond_code 对应的交易code的值
            # timestart 时间开始
            # timeend 时间结束
            res1 = abs((val1["type1_yield"] - val1["type0_yield"])*100)
            # res2 = abs((val1["type1_yield"] - val1["type0_yield"])*100)
            if res1 <= 0:
                res1 = 0
            else:
                res1 = '%.2f' % (res1)
            val1["yidle_std"] = res1
            timestart = val1["timestart"]
            timeend = val1["timeend"]
            time1 = time.mktime(time.strptime(timestart, "%Y-%m-%d %H:%M:%S"))
            # 1622075815
            time2 = time.mktime(time.strptime(timeend, "%Y-%m-%d %H:%M:%S"))
            timers = int(time2 - time1)
            print("获取的timers内容:", time2, time1, timers)
            # res1
            val1["date_std"] = timers
    return arr_object_list
    # print("遍历后的内容:", object_list)
# print()
# basepath = os.path.dirname(os.path.dirname(os.getcwd()))
# file_path = os.path.join(basepath, "static/file/做市商报价2021-05-28.xlsx")
# print("a123", file_path)
# flags = fomat_files(file_path)
# print("获取结果:", flags)
